package com.matt.service.impl;


import com.matt.commons.dto.sso.StaffDTO;
import com.matt.domain.AboutPallet;
import com.matt.domain.AboutVisit;
import com.matt.domain.Leads;
import com.matt.domain.LeadsHistory;
import com.matt.foundation.constant.PermissionConstant;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.model.StatusResponse;
import com.matt.foundation.query.AboutPalletQuery;
import com.matt.foundation.query.AboutVisitQuery;
import com.matt.foundation.utils.CopyUtils;
import com.matt.foundation.utils.DateUtil;
import com.matt.remoteCall.SsoCallService;
import com.matt.repository.AboutPalletRepository;
import com.matt.repository.LeadsHistoryRepository;
import com.matt.repository.LeadsRepository;
import com.matt.service.AboutPalletService;
import com.matt.service.LeadsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import static com.matt.foundation.constant.OperateConstant.OPERATE_TRANSFER;


/**
 * 预约试托业务层
 *
 * @author makejava
 * @since 2025-02-20 11:01:25
 */
@Slf4j
@Service
public class AboutPalletServiceImpl implements AboutPalletService {

	@Resource
    private AboutPalletRepository aboutPalletRepository;

	@Resource
    private LeadsRepository leadsRepository;

    @Resource
    private SsoCallService ssoCallService;

    @Resource
    private LeadsHistoryRepository leadsHistoryRepository;

    @Override
    public AboutPallet save(String ticket,AboutPallet aboutPallet) {
        if(aboutPallet.getType()==2) {
            //根据token查询登录人信息
            StaffDTO staff = ssoCallService.getStaffDTO(ticket);
            //负责人，负责人姓名
            aboutPallet.setStaffId(staff.getId());
            aboutPallet.setStaffName(staff.getRealName());
            aboutPallet.setAreaId(staff.getAreaId());
        }
        if(Objects.isNull(aboutPallet.getGender())){
            aboutPallet.setGender(2);
        }
        aboutPallet.setStatus(2);
        aboutPallet.setCreated(new Date());
        aboutPallet.setChangeStatusVal("未转");
        return aboutPalletRepository.save(aboutPallet);
    }

    @Override
    @Transactional
    public AboutPallet update(String ticket,AboutPallet aboutPallet) {
        //根据token查询登录人信息
        if(aboutPallet.getType()==2){
            StaffDTO staff = ssoCallService.getStaffDTO(ticket);
            aboutPallet.setUpdateUser(staff.getId());
        }
        aboutPallet.setUpdateTime(new Date());
        return aboutPalletRepository.save(aboutPallet);
    }


    @Override
    @Transactional
    public StatusResponse updateLeads(String ticket, AboutPallet aboutPallet){
        //根据token查询登录人信息
        if(aboutPallet.getType()==2){
            StaffDTO staff = ssoCallService.getStaffDTO(ticket);
            aboutPallet.setUpdateUser(staff.getId());
        }
        aboutPallet.setUpdateTime(new Date());
        aboutPallet.setRankp(0);
        //如果转交成为线索
        Leads leads = new Leads();
//        if(aboutPallet.getChangeStatusVal().equals("已转")){
//            BeanUtils.copyProperties(aboutPallet,leads);
//        }

        BeanUtils.copyProperties(aboutPallet,leads);
//        Leads leads1 = leadsRepository.findByMobileAreaId(aboutPallet.getMobile(),aboutPallet.getAreaId());
        Leads leads1 = leadsRepository.findTopByChildNameAndMobileAndAreaIdAndNickNameAndDeletedFalse(aboutPallet.getMobile(),aboutPallet.getMobile(),aboutPallet.getAreaId(), aboutPallet.getNickName());
        if(!Objects.isNull(leads1)){
           return StatusResponse.error(ErrorCode.RECORD_DUPLICATED,"线索已存在");
        }
        leads.setCreated(new Date());
        leads.setClientStatus(5);
        leads.setZhwysStatus("0");
        if(Objects.isNull(aboutPallet.getGender())){
            leads.setGender(2);
        }
        leads.setRankp(0);
        leads.setStaffId(aboutPallet.getStaffId());
        leads.setStaffName(aboutPallet.getStaffName());
        Date date = new Date();
        StaffDTO baseInfo = ssoCallService.getStaffDTO(ticket);

        leads.setChannelId("63a40ecf9ad340678cfce90075eab6ab");
        leadsRepository.save(leads);

        LeadsHistory leadsHistory = new LeadsHistory();
        leadsHistory.setType("leads");
        leadsHistory.setOperationType(OPERATE_TRANSFER);
        leadsHistory.setContent("在 "+ DateUtil.dateToymd(date)+" 将本数据转移给了 \""+aboutPallet.getStaffName()+"\"");
        leadsHistory.setActualFollowDate(date);
        leadsHistory.setLeadsId(leads.getId());
        leadsHistory.setStaffId(baseInfo.getId());
        leadsHistory.setStaffName(baseInfo.getRealName());
        leadsHistory.setStaffHeadImgUrl(baseInfo.getHeadImgUrl());
        leadsHistory.setAreaId(baseInfo.getAreaId());
        leadsHistoryRepository.save(leadsHistory);
        //修改为转交
        return StatusResponse.success(aboutPalletRepository.save(aboutPallet));
    }

    @Override
    public void deleteById(String id) {
        aboutPalletRepository.deleteById(id);
    }

    @Override
    public AboutPallet findById(String id) {
        return aboutPalletRepository.getOne(id);
    }

    @Override
    public AboutPallet wpAdd(AboutPallet aboutPallet) {
        if(Objects.isNull(aboutPallet.getGender())){
            aboutPallet.setGender(2);
        }
        aboutPallet.setStatus(2);
        aboutPallet.setCreated(new Date());
        aboutPallet.setChangeStatusVal("未转");
        return aboutPalletRepository.save(aboutPallet);
    }

    @Override
    public List<AboutPallet> findById(Collection<String> ids) {
        Iterable<AboutPallet> iterable = aboutPalletRepository.findAllById(ids);
        return StreamSupport.stream(iterable.spliterator(), false)
                .collect(Collectors.toList());
    }

    @Override
    public Page<AboutPallet> list(String ticket, AboutPalletQuery aboutPallet) {
        StaffDTO staff = ssoCallService.getStaffDTO(ticket);
        Page<AboutPallet> pallets = null;
        if (ssoCallService.checkStaffPermission(ticket,new String[]{PermissionConstant.TEACH_CLASSES_FULL }) ){
        }else if (ssoCallService.checkStaffPermission(ticket,new String[]{PermissionConstant.TEACH_CLASSES_SALES })) {
            aboutPallet.setStaffId(staff.getId());
        }
        // 模糊查询条件
        Specification<AboutPallet> query = new Specification<AboutPallet>() {
            private static final long serialVersionUID = 1L;
            @Override
            //重新Specification的toPredicate方法
            public Predicate toPredicate(Root<AboutPallet> root, CriteriaQuery<?> query,
                                         CriteriaBuilder criteriaBuilder) {
                List<Predicate > predicates = new ArrayList<Predicate>();
                if (!StringUtils.isEmpty(aboutPallet.getName())) {
                    predicates.add(criteriaBuilder.like(root.get("name"), "%" + aboutPallet.getName() + "%"));
                }
                if (!StringUtils.isEmpty(aboutPallet.getChildName())) {
                    predicates.add(criteriaBuilder.like(root.get("childName"), "%" + aboutPallet.getChildName() + "%"));
                }
                if (null != aboutPallet.getStatus()) {
                    predicates.add(criteriaBuilder.equal(root.get("status"), aboutPallet.getStatus()));
                }
                if (null != aboutPallet.getStaffId()) {
                    predicates.add(criteriaBuilder.equal(root.get("type"), aboutPallet.getStaffId()));
                }
                if (aboutPallet.getInitiateTime() != null) {
                    predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("visitTime"), aboutPallet.getInitiateTime()));
                }
                if (aboutPallet.getEndTime() != null) {
                    predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("visitTime"), aboutPallet.getEndTime()));
                }
                if (aboutPallet.getStaffId() != null) {
                    predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("staffId"), aboutPallet.getStaffId()));
                }
                if (aboutPallet.getAreaId() != null) {
                    predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("areaId"), aboutPallet.getAreaId()));
                }

                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };

        //实现分页
        PageRequest p = PageRequest.of(aboutPallet.getPageNum() - 1, aboutPallet.getPageSize(),
                Sort.by(Sort.Direction.DESC, "created"));
        Page<AboutPallet> pageAll = aboutPalletRepository.findAll(query,p);
        LocalDate date = LocalDate.now();
        if(!pageAll.getContent().isEmpty()){
            pageAll.getContent().forEach(a->{
                if(a.getBirthday()!=null){
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    String formattedDate = formatter.format(a.getBirthday());
                    LocalDate localDate = LocalDate.parse(formattedDate);
                    long monthsBetween = ChronoUnit.MONTHS.between(localDate,date);
                    a.setMonthsDiff(String.valueOf(monthsBetween));
                }
            });
        }
        return pageAll;
    }


    @Override
    public List<AboutPallet> getList(AboutPalletQuery aboutVisit){
        // 模糊查询条件
        Specification<AboutPallet> query = new Specification<AboutPallet>() {
            private static final long serialVersionUID = 1L;
            @Override
            //重新Specification的toPredicate方法
            public Predicate toPredicate(Root<AboutPallet> root, CriteriaQuery<?> query,
                                         CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                if (!StringUtils.isEmpty(aboutVisit.getName())) {
                    predicates.add(criteriaBuilder.like(root.get("name"), "%" + aboutVisit.getName() + "%"));
                }
                if (null != aboutVisit.getStatus()) {
                    predicates.add(criteriaBuilder.equal(root.get("status"), aboutVisit.getStatus()));
                }

                if (null != aboutVisit.getUserId()) {
                    predicates.add(criteriaBuilder.equal(root.get("userId"), aboutVisit.getUserId()));
                }
                if (null != aboutVisit.getMobile()) {
                    predicates.add(criteriaBuilder.equal(root.get("mobile"), aboutVisit.getMobile()));
                }

                if (aboutVisit.getInitiateTime() != null) {
                    predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("visitTime"), aboutVisit.getInitiateTime()));
                }
                if (aboutVisit.getEndTime() != null) {
                    predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("visitTime"), aboutVisit.getEndTime()));
                }
                if (aboutVisit.getStaffId() != null) {
                    predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("staffId"), aboutVisit.getStaffId()));
                }
                if (aboutVisit.getAreaId() != null) {
                    predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("areaId"), aboutVisit.getAreaId()));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        List<AboutPallet> list = aboutPalletRepository.findAll(query);
        if(!list.isEmpty()){
            LocalDate date = LocalDate.now();
            list.forEach(a->{
                if(a.getBirthday()!=null){
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    String formattedDate = formatter.format(a.getBirthday());
                    LocalDate localDate = LocalDate.parse(formattedDate);
                    long monthsBetween = ChronoUnit.MONTHS.between(localDate,date);
                    a.setMonthsDiff(String.valueOf(monthsBetween));
                }
            });
        }
        return list;
    }
}

